1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*!
Convert `isotope` ASTs to terms
*/
use crate::*;
use ast::{Expr, Join, Let, Stmt};
use hayami::{SymbolMap, SymbolTable};

/// A converter for `isotope` ASTs into in-memory representation
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Builder<T = StandardCtx> {
    /// The current symbol table
    symbols: SymbolTable<String, TableEntry, ahash::RandomState>,
    /// The current set of variable types
    vars: Vec<Option<TermId>>,
    /// The default number of join steps
    default_join_steps: u64,
    /// This builder's underlying typing context
    ctx: T,
}

impl<T: Default + TyCtxMut> Default for Builder<T> {
    fn default() -> Self {
        Builder {
            symbols: SymbolTable::default(),
            vars: Vec::new(),
            default_join_steps: 200,
            ctx: T::default(),
        }
    }
}

/// An entry in a symbol table
#[derive(Debug, Clone, PartialEq, Eq)]
struct TableEntry {
    /// The substitution
    term: TermId,
    /// The level of this substitution
    level: u32,
}

impl TableEntry {
    /// Get an entry at a given level
    fn get(&self, level: u32, ctx: &mut (impl ConsCtx + ?Sized)) -> TermId {
        let shift = level - self.level;
        //TODO: error fixing, overflow...
        self.term.shifted(shift as i32, 0, ctx).unwrap()
    }
}

impl<T, M> Builder<T>
where
    T: TyCtxMut<TermEqCtx = M>,
    M: TermEqCtxEdit,
{
    /// Create a new builder for `isotope` values
    #[inline]
    pub fn new(ctx: T) -> Builder<T> {
        Builder {
            symbols: SymbolTable::default(),
            vars: Vec::new(),
            default_join_steps: 200,
            ctx,
        }
    }

    /// Handle a statement
    #[inline]
    pub fn stmt(&mut self, stmt: &Stmt) -> Result<(), Error> {
        match stmt {
            Stmt::Let(stmt) => self.let_(stmt),
            Stmt::Join(stmt) => self.join(stmt),
        }
    }

    /// Handle a let-statement
    #[inline]
    fn let_(&mut self, stmt: &Let) -> Result<(), Error> {
        let value = if let Some(ty) = &stmt.ty {
            self.expr_with(&stmt.value, ty)?
        } else {
            self.expr(&stmt.value)?
        };
        if let Some(ident) = &stmt.ident {
            self.register_subst(ident.clone(), value);
        }
        Ok(())
    }

    /// Handle a join statement
    #[inline]
    fn join(&mut self, stmt: &Join) -> Result<(), Error> {
        let source = self.expr(&stmt.source)?;
        let target = stmt
            .target
            .as_deref()
            .map(|target| self.expr(target))
            .transpose()?;
        if let Some(target) = &target {
            match source.eq_in(target, self.ctx.eq_ctx()) {
                Some(true) => return Ok(()),
                Some(false) => return Err(Error::TermMismatch),
                None if stmt.form == ast::Form::Null => return Err(Error::TermUnificationFailure),
                None => {}
            }
        }
        let max_steps = stmt.work_limit.unwrap_or(self.default_join_steps);
        let cfg = NormalCfg {
            max_steps,
            eta: stmt.form.eta(),
            head: stmt.form.head(),
            sub: stmt.form.sub(),
        };
        let redex = source.reduce_until(cfg, target.clone(), &mut self.ctx)?;
        if let Some(target) = &target {
            if let Some(redex) = redex {
                match redex.eq_in(target, self.ctx.eq_ctx()) {
                    Some(true) => {}
                    Some(false) => return Err(Error::TermMismatch),
                    None => return Err(Error::TermUnificationFailure),
                }
                self.ctx.eq_ctx().shallow_cons_make_term_eq(&source, &redex);
            } else {
                // No change was made, and equality was already checked beforehand
                return Err(Error::TermUnificationFailure);
            }
        }
        Ok(())
    }

    /// Build an expression into a term
    #[inline]
    pub fn expr(&mut self, expr: &Expr) -> Result<TermId, Error> {
        let result = match expr {
            Expr::Ident(ident) => self.ident(&ident[..])?,
            Expr::Var(ix) => self.var(*ix),
            Expr::App(app) => self.app(app)?,

            Expr::Lambda(lambda) => self.lambda(lambda)?.into_id_with(self.ctx.cons_ctx()),
            Expr::Pi(pi) => self.pi(pi)?.into_id_with(self.ctx.cons_ctx()),
            Expr::Universe(universe) => self.universe(*universe)?.into_id_with(self.ctx.cons_ctx()),

            Expr::Enum(enum_) => self.enum_(enum_)?.into_id_with(self.ctx.cons_ctx()),
            Expr::Variant(variant) => self.variant(variant)?.into_id_with(self.ctx.cons_ctx()),
            Expr::Bool => self.get_bool().into_id_with(self.ctx.cons_ctx()),
            Expr::Boolean(boolean) => self.boolean(*boolean).into_id_with(self.ctx.cons_ctx()),

            Expr::Case(case) => self.case(case)?.into_id_with(self.ctx.cons_ctx()),

            Expr::Annotated(annotated) => self.annotated(annotated)?,
            Expr::Scope(scope) => self.scope(scope)?,

            _ => return Err(Error::NotImplemented),
        };
        Ok(result)
    }

    /// Get a variable
    #[inline]
    pub fn get_var(&mut self, ix: u32) -> Option<Option<TermId>> {
        //TODO: overflow et al
        if (ix as usize) < self.vars.len() {
            let rev_ix = self.vars.len() - 1 - (ix as usize);
            //TODO: fix this...
            self.vars[rev_ix]
                .shifted(
                    self.vars.len() as i32 - 1 - ix as i32,
                    0,
                    self.ctx.cons_ctx(),
                )
                .ok()
        } else {
            None
        }
    }

    /// Build a variable
    #[inline]
    pub fn var(&mut self, ix: u32) -> TermId {
        let ty = self.get_var(ix);
        Var::new_unchecked(ix, ty.flatten()).into_id_with(self.ctx.cons_ctx())
    }

    /// Build an identifier
    #[inline]
    pub fn ident(&mut self, ident: &str) -> Result<TermId, Error> {
        if let Some(entry) = self.symbols.get(ident) {
            let result = entry.get(self.vars.len() as u32, self.ctx.cons_ctx());
            Ok(result)
        } else {
            Err(Error::UndefinedSymbol)
        }
    }

    /// Build an application
    #[inline]
    pub fn app(&mut self, app: &ast::App) -> Result<TermId, Error> {
        self.app_slice(&app.0[..])
    }

    /// Build an application from a slice of expressions
    #[inline]
    pub fn app_slice<E>(&mut self, slice: &[E]) -> Result<TermId, Error>
    where
        E: Borrow<Expr>,
    {
        let first = if let Some(first) = slice.get(0) {
            self.expr(first.borrow())?
        } else {
            return Err(Error::NotImplemented); // return nil
        };
        self.apply_to_slice(first, &slice[1..])
    }

    /// Apply a term to a slice of expressions
    #[inline]
    pub fn apply_to_slice<E>(&mut self, func: TermId, slice: &[E]) -> Result<TermId, Error>
    where
        E: Borrow<Expr>,
    {
        let first = if let Some(first) = slice.get(0) {
            self.expr(first.borrow())?
        } else {
            return Ok(func);
        };
        let app = self
            .construct_app(func, first)?
            .into_id_with(self.ctx.cons_ctx());
        self.apply_to_slice(app, &slice[1..])
    }

    /// Build an application within this context
    #[inline]
    pub fn construct_app(&mut self, left: TermId, right: TermId) -> Result<App, Error> {
        //TODO: typecheck, etc
        Ok(App::new_direct(left, right, None, &mut self.ctx))
    }

    /// Build a lambda function
    #[inline]
    pub fn lambda(&mut self, lambda: &ast::Lambda) -> Result<Lambda, Error> {
        let param_ty = lambda
            .param_ty
            .as_ref()
            .map(|param_ty| self.expr(param_ty))
            .transpose()?;
        let result = self.parametrized(
            param_ty.as_ref(),
            lambda.param_name.as_deref(),
            &lambda.result,
        )?;
        Ok(Lambda::new_direct(param_ty, result, self.ctx.cons_ctx()))
    }

    /// Build a pi type
    #[inline]
    pub fn pi(&mut self, pi: &ast::Pi) -> Result<Pi, Error> {
        let param_ty = self.expr(&pi.param_ty)?;
        let result = self.parametrized(
            Some(&param_ty),
            pi.param_name.as_ref().map(Option::as_deref).flatten(),
            &pi.result,
        )?;
        //TODO: typecheck?
        Ok(Pi::new(param_ty, result, self.ctx.cons_ctx()))
    }

    /// Build a parametrized term
    #[inline]
    pub fn parametrized(
        &mut self,
        param_ty: Option<&TermId>,
        param_name: Option<&str>,
        result: &ast::Expr,
    ) -> Result<TermId, Error> {
        self.vars.push(param_ty.cloned());
        let nameframe = if let Some(name) = param_name {
            let var = self.var(0);
            self.symbols.push();
            self.register_subst(name.to_string(), var);
            true
        } else {
            false
        };
        let result = self.expr(result);
        if nameframe {
            self.symbols.pop();
        }
        self.vars.pop();
        result
    }

    /// Build a typing universe
    #[inline]
    pub fn universe(&mut self, universe: ast::Universe) -> Result<Universe, Error> {
        Universe::try_new(universe.level(), universe.is_var())
    }

    /// Build an enumeration
    pub fn enum_(&mut self, enum_: &ast::Enum) -> Result<Enum, Error> {
        let set = enum_.0.iter().cloned().collect();
        Ok(Enum::new(set))
    }

    /// Build a variant
    pub fn variant(&mut self, variant: &str) -> Result<Variant, Error> {
        //TODO: improve this? reduce allocations?
        let ty = Enum::new(StringSet::singleton(variant)).into_id_with(self.ctx.cons_ctx());
        Variant::new_direct(variant, ty)
    }

    /// Build the type of booleans
    #[inline]
    pub fn get_bool(&mut self) -> Bool {
        Bool::default()
    }

    /// Build a boolean
    #[inline]
    pub fn boolean(&mut self, boolean: bool) -> Boolean {
        Boolean::new_unchecked(boolean, None)
    }

    /// Build a case statement
    #[inline]
    pub fn case(&mut self, case: &ast::Case) -> Result<Case, Error> {
        //TODO: clean this up, bigtime...
        if case.0.len() == 0 {
            return Err(Error::NotImplemented);
        }
        let target_0 = self.expr(&case.0[0].pattern)?;
        let matches = target_0
            .ty()
            .ok_or(Error::CannotInfer)?
            .clone_into_id_with(self.ctx.cons_ctx());
        let mut branches: SmallVec<[_; 16]> = case
            .0
            .iter()
            .enumerate()
            .map(|(i, branch)| {
                let result = self.expr(&branch.result)?;
                let tmp;
                let target = if i == 0 {
                    &target_0
                } else {
                    tmp = self.expr(&branch.pattern)?;
                    &tmp
                };
                //TODO: clean up this error message...
                let ix = Case::get_match(target, &matches)?.ok_or(Error::OutOfGas)?;
                Ok((ix, result))
            })
            .collect::<Result<_, _>>()?;
        branches.sort_by_key(|(ix, _)| *ix);
        let len = branches.len();
        branches.dedup_by_key(|(ix, _)| *ix);
        if branches.len() < len {
            warn!(
                "{} shadowed branches in case statement",
                len - branches.len()
            )
        }
        let cases: SmallVec<[_; 32]> = branches.into_iter().map(|(_ix, b)| b).collect();
        Case::new_minimal((&cases[..]).into(), matches, &mut self.ctx)
    }

    /// Build an annotated term
    #[inline]
    pub fn annotated(&mut self, annotated: &ast::Annotated) -> Result<TermId, Error> {
        self.expr_with(&annotated.term, &annotated.ty)
    }

    /// Build a term with an annotation
    #[inline]
    pub fn expr_with(&mut self, expr: &Expr, annot: &Expr) -> Result<TermId, Error> {
        let annot = self.expr(&annot)?;
        let term = self.expr(&expr)?;
        let coerced = term.coerce(Some(annot), &mut self.ctx)?.unwrap_or(term);
        Ok(coerced)
    }

    /// Build a scope
    #[inline]
    pub fn scope(&mut self, scope: &ast::Scope) -> Result<TermId, Error> {
        let mut errno = Ok(());
        self.ctx.reset_unbound()?;
        self.symbols.push();
        for stmt in &scope.stmts {
            if let Err(err) = self.stmt(stmt) {
                errno = Err(err);
                continue;
            }
        }
        let result = match errno {
            Ok(()) => self.expr(&scope.result),
            Err(err) => Err(err),
        };
        self.symbols.pop();
        result
    }

    /// Register a substitution
    #[inline]
    pub fn register_subst(&mut self, symbol: String, subst: TermId) {
        self.symbols.insert(
            symbol,
            TableEntry {
                term: subst,
                level: self.vars.len() as u32,
            },
        )
    }

    /// Get this builder's underlying typing context
    #[inline]
    pub fn ctx(&mut self) -> &mut T {
        &mut self.ctx
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn untyped_round_trip() {
        let examples = [
            "#true",
            "#false",
            "#bool",
            "λx.x",
            "(λx.x)(λx.x)",
            "{
                #let x = #true;
                x
            }",
            "#enum { 'x 'y 'z }",
            "#case { #true => #false; #false => #true }",
        ];

        let ctx = StandardCtx::default();
        let mut builder = Builder::new(ctx);

        for example in examples {
            let (rest, parsed) = isotope_parser::expr(example).unwrap();
            assert_eq!(rest, "");
            let built = builder.expr(&parsed).unwrap();
            let ast = built.to_ast_in(&mut Untyped).unwrap();
            //NOTE: ast may not be equal to parsed, as the builder may e.g. discard variable names and unpack scopes
            let built_ast = builder.expr(&ast).unwrap();
            //NOTE: we check for pointer equality since this builder is consing
            assert_eq!(built.as_ptr(), built_ast.as_ptr());
        }
    }

    #[test]
    fn basic_head_reduction() {
        let program = [
            ("#let i = λx:#bool.x;", true),
            ("#eq (i #true) => #true;", false),
            ("#eq (i #false) => #false;", false),
            ("#head (i #true) => #true;", true),
            ("#eq (i #true) => #true;", true),
            ("#eq (i #false) => #false;", false),
            ("#head (i #false) => #false;", true),
            ("#eq (i #true) => #true;", true),
            ("#eq (i #false) => #false;", true),
            ("#head #true => #false;", false),
            // We repeat this twice to make sure false facts are not being entered into the database
            ("#head #true => #false;", false),
            ("#head (i #true) => #false;", false),
        ];

        let ctx = StandardCtx::default();
        let mut builder = Builder::new(ctx);

        for (line, pass) in program {
            let (rest, parsed) = isotope_parser::stmt(line).unwrap();
            assert_eq!(rest, "");
            let result = builder.stmt(&parsed);
            if pass {
                assert_eq!(result, Ok(()))
            } else {
                assert!(result.is_err())
            }
        }
    }
}